/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * HistoryPanel.java
 *
 * Created on 2011-9-17, 20:49:09
 */
package com.football.lottery.ui;

import com.football.lottery.services.DAOServices;
import com.football.lottery.obj.FootballLottery;
import com.football.lottery.obj.GameItem;
import com.football.lottery.services.CombinServices;
import com.football.lottery.services.IOServices;
import java.awt.event.ItemEvent;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.swing.JCheckBox;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableColumn;

/**
 *
 * @author JingWen
 */
public class HistoryPanel extends javax.swing.JPanel
{
  private MainFrame mainFrame;
  private IOServices ioServices;
  private DAOServices DAOServices;
  private CombinServices combinServices;
  private GameTableModel tModel;
  Integer periodNo;
  private String[] columnName = {"Period No", "Type", "Time", "Host", "Score", "Guest", "CompensationRate", "My Bet", "Precaution"};

  /** Creates new form HistoryPanel */
  HistoryPanel(MainFrame mainFrame)
  {
    initComponents();
    
    this.mainFrame = mainFrame;
    ioServices = new IOServices();
    DAOServices = new DAOServices();
    combinServices = new CombinServices();
    
    tModel = new GameTableModel(new Object[0][0], columnName);
    dataTable.setModel(tModel);
    dataTable.setDefaultRenderer(Object.class, new JTableCellRenderer());
    dataTable.getColumn("My Bet").setCellEditor(new CheckboxCellEditor(new JCheckBox(), new CheckboxPanel(null)));
    dataTable.getColumn("Precaution").setCellEditor(new CheckboxCellEditor(new JCheckBox(), new CheckboxPanel(null)));
  }

  /** This method is called from within the constructor to
   * initialize the form.
   * WARNING: Do NOT modify this code. The content of this method is
   * always regenerated by the Form Editor.
   */
  @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        periodNoComboBox = new javax.swing.JComboBox();
        jLabel2 = new javax.swing.JLabel();
        stopTimeLabel = new javax.swing.JLabel();
        jPanel2 = new javax.swing.JPanel();
        jPanel4 = new javax.swing.JPanel();
        confirmBetButton = new javax.swing.JButton();
        amountLabel = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        countButton = new javax.swing.JButton();
        jLabel6 = new javax.swing.JLabel();
        hitLabel = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jPanel5 = new javax.swing.JPanel();
        jPanel3 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        dataTable = new javax.swing.JTable();

        setLayout(new java.awt.BorderLayout());

        jPanel1.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT));

        jLabel1.setText(org.openide.util.NbBundle.getMessage(HistoryPanel.class, "HistoryPanel.jLabel1.text")); // NOI18N
        jPanel1.add(jLabel1);

        periodNoComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        jPanel1.add(periodNoComboBox);

        jLabel2.setText(org.openide.util.NbBundle.getMessage(HistoryPanel.class, "HistoryPanel.jLabel2.text")); // NOI18N
        jPanel1.add(jLabel2);

        stopTimeLabel.setText(org.openide.util.NbBundle.getMessage(HistoryPanel.class, "HistoryPanel.stopTimeLabel.text")); // NOI18N
        jPanel1.add(stopTimeLabel);

        add(jPanel1, java.awt.BorderLayout.PAGE_START);

        jPanel2.setLayout(new java.awt.BorderLayout());

        jPanel4.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.RIGHT));

        confirmBetButton.setText(org.openide.util.NbBundle.getMessage(HistoryPanel.class, "HistoryPanel.confirmBetButton.text")); // NOI18N
        confirmBetButton.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        confirmBetButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                confirmBetButtonActionPerformed(evt);
            }
        });
        jPanel4.add(confirmBetButton);

        amountLabel.setText(org.openide.util.NbBundle.getMessage(HistoryPanel.class, "HistoryPanel.amountLabel.text")); // NOI18N
        jPanel4.add(amountLabel);

        jLabel7.setText(org.openide.util.NbBundle.getMessage(HistoryPanel.class, "HistoryPanel.jLabel7.text")); // NOI18N
        jPanel4.add(jLabel7);

        countButton.setText(org.openide.util.NbBundle.getMessage(HistoryPanel.class, "HistoryPanel.countButton.text")); // NOI18N
        countButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                countButtonActionPerformed(evt);
            }
        });
        jPanel4.add(countButton);

        jLabel6.setText(org.openide.util.NbBundle.getMessage(HistoryPanel.class, "HistoryPanel.jLabel6.text")); // NOI18N
        jPanel4.add(jLabel6);

        hitLabel.setText(org.openide.util.NbBundle.getMessage(HistoryPanel.class, "HistoryPanel.hitLabel.text")); // NOI18N
        jPanel4.add(hitLabel);

        jLabel5.setText(org.openide.util.NbBundle.getMessage(HistoryPanel.class, "HistoryPanel.jLabel5.text")); // NOI18N
        jPanel4.add(jLabel5);

        jPanel2.add(jPanel4, java.awt.BorderLayout.CENTER);

        jPanel5.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.RIGHT));
        jPanel2.add(jPanel5, java.awt.BorderLayout.PAGE_START);

        add(jPanel2, java.awt.BorderLayout.PAGE_END);

        jPanel3.setMinimumSize(new java.awt.Dimension(600, 385));
        jPanel3.setPreferredSize(new java.awt.Dimension(600, 385));
        jPanel3.setLayout(new java.awt.BorderLayout());

        dataTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Period No", "Type", "Time", "Host", "Score", "Guest", "CompensationRate", "My Bet", "Precaution"
            }
        ));
        dataTable.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_NEXT_COLUMN);
        dataTable.setRowHeight(25);
        jScrollPane1.setViewportView(dataTable);
        dataTable.getColumnModel().getColumn(0).setHeaderValue(org.openide.util.NbBundle.getMessage(HistoryPanel.class, "HistoryPanel.dataTable.columnModel.title0")); // NOI18N
        dataTable.getColumnModel().getColumn(1).setHeaderValue(org.openide.util.NbBundle.getMessage(HistoryPanel.class, "HistoryPanel.dataTable.columnModel.title1")); // NOI18N
        dataTable.getColumnModel().getColumn(2).setHeaderValue(org.openide.util.NbBundle.getMessage(HistoryPanel.class, "HistoryPanel.dataTable.columnModel.title2")); // NOI18N
        dataTable.getColumnModel().getColumn(3).setHeaderValue(org.openide.util.NbBundle.getMessage(HistoryPanel.class, "HistoryPanel.dataTable.columnModel.title3")); // NOI18N
        dataTable.getColumnModel().getColumn(4).setHeaderValue(org.openide.util.NbBundle.getMessage(HistoryPanel.class, "HistoryPanel.dataTable.columnModel.title4")); // NOI18N
        dataTable.getColumnModel().getColumn(5).setHeaderValue(org.openide.util.NbBundle.getMessage(HistoryPanel.class, "HistoryPanel.dataTable.columnModel.title5")); // NOI18N
        dataTable.getColumnModel().getColumn(6).setHeaderValue(org.openide.util.NbBundle.getMessage(HistoryPanel.class, "HistoryPanel.dataTable.columnModel.title6")); // NOI18N
        dataTable.getColumnModel().getColumn(7).setHeaderValue(org.openide.util.NbBundle.getMessage(HistoryPanel.class, "HistoryPanel.dataTable.columnModel.title7")); // NOI18N
        dataTable.getColumnModel().getColumn(8).setHeaderValue(org.openide.util.NbBundle.getMessage(HistoryPanel.class, "HistoryPanel.dataTable.columnModel.title8")); // NOI18N

        jPanel3.add(jScrollPane1, java.awt.BorderLayout.CENTER);

        add(jPanel3, java.awt.BorderLayout.CENTER);
    }// </editor-fold>//GEN-END:initComponents

  private void countButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_countButtonActionPerformed
  {//GEN-HEADEREND:event_countButtonActionPerformed
    // TODO add your handling code here:
  }//GEN-LAST:event_countButtonActionPerformed

  private void confirmBetButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_confirmBetButtonActionPerformed
  {//GEN-HEADEREND:event_confirmBetButtonActionPerformed
    this.confirmBet();
  }//GEN-LAST:event_confirmBetButtonActionPerformed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel amountLabel;
    private javax.swing.JButton confirmBetButton;
    private javax.swing.JButton countButton;
    private javax.swing.JTable dataTable;
    private javax.swing.JLabel hitLabel;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JComboBox periodNoComboBox;
    private javax.swing.JLabel stopTimeLabel;
    // End of variables declaration//GEN-END:variables

  public void addComboBoxListener()
  {
    periodNoComboBox.addItemListener(new java.awt.event.ItemListener()
    {
      @Override
      public void itemStateChanged(java.awt.event.ItemEvent evt)
      {
        periodNoComboBoxItemStateChanged(evt);
      }
    });
  }
  
  private void periodNoComboBoxItemStateChanged(java.awt.event.ItemEvent evt)                                                  
  {                                                      
    final java.awt.event.ItemEvent boxEvt = evt;
    new Thread(new Runnable()
    {
      @Override
      public void run()
      {
        if (ItemEvent.SELECTED == boxEvt.getStateChange())
        {
          refresh();
        }
      }
    }).start();
  }                                

  private void refresh()
  {
    this.periodNo = (Integer) this.periodNoComboBox.getSelectedItem();
    FootballLottery fbl = mainFrame.getFblServices().getFootballLotteryByPeriodNo(periodNo);
    this.stopTimeLabel.setText(fbl.getStopTime());
    List games = fbl.getGames();
    this.showDateToTable(games);
  }
  
  public void refreshUI()
  {
    this.setPeriodNos();
    this.refresh();
  }
    
  private void setPeriodNos()
  {
    this.periodNoComboBox.removeAllItems();
    List periodNos = mainFrame.getFblServices().getAllPeriodNos();
    for (Object obj : periodNos)
    {
      this.periodNoComboBox.addItem((Integer) obj);
    }
  }
  
  public void showDateToTable(int periodNo)
  {
  }

  public void showDateToTable(List games)
  {
    if (games == null || games.isEmpty())
    {
      return;
    }
    tModel.removeAllRows();
    tModel.addItemRows(games);
  }
  
  public List getGameItemsFromTable()
  {
    return tModel.getItemRows();
  }

  private void confirmBet()
  {
    List newGameItems = this.tModel.getItemRows();
    Map betMap = new HashMap();
    Map preBetMap = new HashMap();
    
    for (Object obj : newGameItems)
    {
      GameItem item = (GameItem) obj;
      item.setPeriodNo(this.periodNo);
      int orderNo = item.getOrderNo();
      String bet = item.getBet();
      String preBet = item.getPreventiveBet();
      
      if (bet == null || bet.length() <= 0)
      {
        JOptionPane.showMessageDialog(this, "Make sure that you have choose " + orderNo + " !");
        return;
      }
      betMap.put(orderNo, bet);
      if (preBet != null && preBet.length() > 0)
      {
        preBetMap.put(orderNo, preBet);
      }
    }
    String preventionNo = JOptionPane.showInputDialog(this, "How many games you want to prevent? \\n e.g: 3,4,5");
    Set preNos = new HashSet();
    if (preventionNo != null && preventionNo.length() > 0)
    {
      String[] preventNos = preventionNo.split(","); 
      for (int i = 0; i < preventNos.length; i++)
      {
        try
        {
          preNos.add(Integer.parseInt(preventNos[i].trim()));
        }
        catch (NumberFormatException e)
        {
          JOptionPane.showMessageDialog(this, "Wrong number format!");
          return;
        }
      }
    }
    
    List betList = this.combinServices.genBetList(betMap, preBetMap, preNos);
    double betAmount = (double) betList.size() * 2;
    this.amountLabel.setText("￥" + betAmount);
    this.ioServices.printBetList(betList, this.periodNo);
    this.DAOServices.updateBetAmount(this.periodNo, betAmount);
    this.DAOServices.updateGames(newGameItems);
  }
  
   private void fitTableColumns(JTable myTable)
  {
    myTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    JTableHeader header = myTable.getTableHeader();
    int rowCount = myTable.getRowCount();
    Enumeration columns = myTable.getColumnModel().getColumns();
    while (columns.hasMoreElements())
    {
      TableColumn column = (TableColumn) columns.nextElement();
      int col = header.getColumnModel().getColumnIndex(column.getIdentifier());
      int width = (int) header.getDefaultRenderer().getTableCellRendererComponent(myTable, column.getIdentifier(), 
          false, false, -1, col).getPreferredSize().getWidth();
      for (int row = 0; row < rowCount; row++)
      {
        int preferedWidth = (int) myTable.getCellRenderer(row, col).getTableCellRendererComponent(myTable, 
            myTable.getValueAt(row, col), false, false, row, col).getPreferredSize().getWidth();
        width = Math.max(width, preferedWidth);
      }
      header.setResizingColumn(column); // 此行很重要
      column.setWidth(width + myTable.getIntercellSpacing().width);
    }
  }
}
